package com.begamer.card.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import sun.misc.BASE64Decoder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.begamer.card.common.CommParams;
import com.begamer.card.common.Constant;
import com.begamer.card.common.RSASignature;
import com.begamer.card.common.dao.hibernate.CommDao;
import com.begamer.card.common.util.AES;
import com.begamer.card.common.util.Base64_2;
import com.begamer.card.common.util.CpTransSyncSignValid;
import com.begamer.card.common.util.MD5;
import com.begamer.card.common.util.PayCore;
import com.begamer.card.common.util.RSAEncrypt;
import com.begamer.card.common.util.RSAEncrypt2;
import com.begamer.card.common.util.RSASignature2;
import com.begamer.card.common.util.RequestUtil;
import com.begamer.card.common.util.StringUtil;
import com.begamer.card.common.util.TestMd5;
import com.begamer.card.common.util.Util;
import com.begamer.card.common.util.binRead.RechargeData;
import com.begamer.card.common.util.binRead.ServersData;
import com.begamer.card.json.CoolpadPayJson;
import com.begamer.card.json.ErrorJson;
import com.begamer.card.json.HaimaPayJson;
import com.begamer.card.json.ItoolsPayJson;
import com.begamer.card.json.PPPayJson;
import com.begamer.card.json.PayBackJson;
import com.begamer.card.json.PayExtraJson;
import com.begamer.card.json.PayJson;
import com.begamer.card.json.TDJson;
import com.begamer.card.json.XyResultJson;
import com.begamer.card.log.ErrorLogger;
import com.begamer.card.log.MemLogger;
import com.begamer.card.model.pojo.PayInfo;
import com.begamer.card.model.pojo.PayOrder;

public class PayController extends AbstractMultiActionController
{
	private static final Logger memlogger = MemLogger.logger;
	private static final Logger errorlogger = ErrorLogger.logger;
	private static final Logger logger = Logger.getLogger(PayController.class);

	@Autowired
	private CommDao commDao;
	
	private static final String appkey ="NkQxM0UwMTc4RDU4OUMwRDg1OEJEMDhFMDkzQTA2MEU4Q0Q4NzE0M09UWXdNall4TURBNE5EZzBOelU0T1RjeU15c3lNRGM0TlRVeE5qTXdPVEEyTnpJNE16YzROVEEwT0RJNU56WXdPRGd4T1RreU9UZzVPREU9";

	/**
	 * @Title: post
	 * @Description: 接收蜂巢消费request
	 *               请求地址：http://127.0.0.1:8080/card_server_pay/pay
	 *               .htm?action=post
	 * @param request
	 * @param response
	 */
	public ModelAndView post(HttpServletRequest request,
			HttpServletResponse response)
	{
		String content = RequestUtil.readParams(request);
		if (content == null || content.trim().length() == 0)
		{
			memlogger.warn("消息为空");
		} else
		{
			try
			{
				byte[] byteDecoded = AES.aesDecryptForPay(CommParams
						.getInstance().getPay_key_gc(), Base64
						.decodeBase64(content.getBytes()), 0);
				String contentDecoded = new String(byteDecoded, "utf-8");
				memlogger.info("本次消费信息(蜂巢)：" + contentDecoded);
				// 解析json
				PayJson pj = JSON.toJavaObject(
						JSON.parseObject(contentDecoded), PayJson.class);
				PayExtraJson pej = JSON.toJavaObject(JSON.parseObject(pj
						.getExtraData()), PayExtraJson.class);
				// 向游戏服务器请求
				if (pj.getState().equals("1"))
				{
					RechargeData rData =RechargeData.getRechargeData(pej.getRechargeId());
					if(rData.cost==StringUtil.getInt(pj.getConsumeValue()))
					{
						notifyGameServer(pj.getGameServerZone(), pej.getPlayerId()
								+ "", pej.getRechargeId() + "", pj
								.getConsumeValue());
					}
					else
					{
						memlogger.info("玩家非法充值：支付"+pj.getConsumeValue()+"应该"+rData.cost);
					}
					
				} else
				{
					memlogger.info("蜂巢返回消费结果state为：" + pj.getState()
							+ ", 故消费失败，不去加水晶");
				}
				// 保存消费信息
				PayInfo pi = PayInfo.createPayInfo(pj);
				try
				{
					commDao.save(pi);
				} catch (Exception e)
				{
					errorlogger.error("保存消费信息出错", e);
				}
				// 通知talkingdata
				if (pi.getState().equals("1"))
				{
					notifyTalkingData(pi);
				}
			} catch (Exception e)
			{
				errorlogger.error("解密消费消息出错", e);
			}
		}

		// 返回response
		PrintWriter out = null;
		try
		{
			response.setContentType("text/xml");
			out = response.getWriter();
			out.println("<?xml version=" + "\"1.0\"" + " encoding="
					+ "\"UTF-8\"" + "?>");
			out.println("<result>");
			out.println("success");
			out.println("</result>");
		} catch (Exception e)
		{
			errorlogger.error(e.toString(), e);
		} finally
		{
			out.close();
		}
		return null;
	}

	/**
	 * 云点友游 lt@2014-6-27 上午10:48:43
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView pay_cypp(HttpServletRequest request,
			HttpServletResponse response)
	{
		String uid = request.getParameter("uid");// 用户ID
		String order_sn = request.getParameter("order_sn");// 友游内部流水号
		String order_number = request.getParameter("order_number");// 第三方游戏订单号
		String amount = request.getParameter("amount");// 交易金额（单位：元）
		String time = request.getParameter("time");// 发起通知请求时间(秒)
		String status = request.getParameter("status");// 交易状态（只有1为交易成功）
		String sign = request.getParameter("sign");// 请求签名

		String msg = "amount=" + amount + "&order_number=" + order_number
				+ "&order_sn=" + order_sn + "&status=" + status + "&time="
				+ time + "&uid=" + uid + "@"
				+ CommParams.getInstance().getPay_key_cpyy();
		memlogger.info("本次消费信息(云点联动):" + msg);
		String sign2 = TestMd5.md5_32(msg);
		String result = "SUCCESS";
		if (sign.equals(sign2))
		{
			if (status.trim().equals("1"))
			{
				// 更新订单信息
				PayOrder po = null;
				try
				{
					po = commDao.getPayOrder(StringUtil.getInt(order_number));
					if (po == null)
					{
						errorlogger.error("没有这个订单:"
								+ StringUtil.getInt(order_number));
					} else
					{
						po.setStatus(1);
						commDao.saveOrUpdate(po);
					}
				} catch (Exception e)
				{
					errorlogger.error("更新订单信息出错", e);
				}
				// 保存支付信息
				String serverId = "";
				String extraData = null;
				PayInfo pi = null;
				try
				{
					if (po != null)
					{
						extraData = po.getExtra();
						serverId = po.getServerId();
					}
					// 保存支付记录
					pi = PayInfo
							.createPayInfo(uid,
									StringUtil.getDateTime(StringUtil
											.getInt(time) * 1000L), "1",
									amount, extraData, serverId, order_sn,
									order_number);
					commDao.save(pi);
				} catch (Exception e)
				{
					errorlogger.error("保存支付信息出错", e);
				}
				// 通知游戏服务器
				try
				{
					if (extraData != null)
					{
						PayExtraJson pej = JSON.toJavaObject(JSON
								.parseObject(extraData), PayExtraJson.class);
						RechargeData rData =RechargeData.getRechargeData(pej.rechargeId);
						if(rData.cost==StringUtil.getInt(amount))
						{
							notifyGameServer(serverId, pej.playerId + "",
									pej.rechargeId + "", amount);
						}
						else
						{
							memlogger.info("玩家非法充值：支付"+amount+"应该"+rData.cost);
						}
					}
				} catch (Exception e)
				{
					errorlogger.error("通知游戏服务器出错", e);
				}
				// 通知talkingdata
				notifyTalkingData(pi);
			}
		} else
		{
			result = "FAILED";
			memlogger.info("云点联动sign:" + sign);
			memlogger.info("本地sign:" + sign2);
		}
		// 返回response
		PrintWriter out = null;
		try
		{
			response.setContentType("text/html;charset=UTF-8");
			out = response.getWriter();
			out.println(result);
			out.flush();
		} catch (Exception e)
		{
			errorlogger.error("返回信息出错", e);
		} finally
		{
			out.close();
		}
		return null;
	}

	/**
	 * 同步推 lt@2014-6-27 上午10:48:43
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView pay_tb(HttpServletRequest request,
			HttpServletResponse response)
	{
		String source = request.getParameter("source");// 数据来源，默认值tongbu
		String trade_no = request.getParameter("trade_no");// 第三方游戏订单号
		String amount = request.getParameter("amount");// 金额，单位为分
		String partner = request.getParameter("partner");// 游戏编号--同步游戏联运平台为游戏分配的唯一编号
		String paydes = request.getParameter("paydes");// 支付说明
		String debug = request.getParameter("debug");// 是否调试模式(判断订单是否是测试订单)
		String tborder = request.getParameter("tborder");// 同步订单号
		String sign = request.getParameter("sign");// 签名-将以上参数加key 后得到的签名

		String msg = "source=" + source + "&trade_no=" + trade_no + "&amount="
				+ amount + "&partner=" + partner + "&paydes=" + paydes
				+ "&debug=" + debug + "&tborder=" + tborder + "&key="
				+ CommParams.getInstance().getPay_key_tb();
		memlogger.info("本次消费信息(同步推):" + msg);
		String sign2 = TestMd5.md5_32(msg);
		String result = "success";
		if (sign.equals(sign2))
		{
			int gameOrder = StringUtil.getInt(trade_no) - Constant.TbOrder;
			memlogger.info("订单号(同步推)表象:" + trade_no);
			memlogger.info("订单号(同步推)实际:" + gameOrder);
			// 更新订单信息
			PayOrder po = null;
			try
			{
				po = commDao.getPayOrder(gameOrder);
				if (po == null)
				{
					errorlogger.error("没有这个订单:" + gameOrder);
				} else
				{
					po.setStatus(1);
					commDao.saveOrUpdate(po);
				}
			} catch (Exception e)
			{
				errorlogger.error("更新订单信息出错", e);
			}
			// 保存支付信息
			String serverId = "";
			String extraData = null;
			PayInfo pi = null;
			// 分换算成元
			int value = StringUtil.getInt(amount);
			value = value / 100;
			try
			{
				if (po != null)
				{
					extraData = po.getExtra();
					serverId = po.getServerId();
				}
				// 保存支付记录

				pi = PayInfo.createPayInfo(null, StringUtil.getDateTime(System
						.currentTimeMillis()), "1", value + "", extraData,
						serverId, tborder, gameOrder + "");
				commDao.save(pi);
			} catch (Exception e)
			{
				errorlogger.error("保存支付信息出错", e);
			}
			// 通知游戏服务器
			try
			{
				if (extraData != null)
				{
					PayExtraJson pej = JSON.toJavaObject(JSON
							.parseObject(extraData), PayExtraJson.class);
					RechargeData rData =RechargeData.getRechargeData(pej.rechargeId);
					if(rData.cost==value)
					{
						notifyGameServer(serverId, pej.playerId + "",
								pej.rechargeId + "", value + "");
					}
					else
					{
						memlogger.info("玩家非法充值：支付"+value+"应该"+rData.cost);
					}
					
				}
			} catch (Exception e)
			{
				errorlogger.error("通知游戏服务器出错", e);
			}
			// 通知talkingdata
			notifyTalkingData(pi);
		} else
		{
			result = "failed";
			memlogger.info("同步推sign:" + sign);
			memlogger.info("本地sign:" + sign2);
		}
		// 返回response
		PrintWriter out = null;
		try
		{
			response.setContentType("text/html;charset=UTF-8");
			out = response.getWriter();
			out.println("{\"status\":\"" + result + "\"}");
			out.flush();
		} catch (Exception e)
		{
			errorlogger.error("返回信息出错", e);
		} finally
		{
			out.close();
		}
		return null;
	}

	// ==当乐==//
	public ModelAndView pay_dl(HttpServletRequest request,
			HttpServletResponse response)
	{
		String result = request.getParameter("result");// 支付结果，固定值。“1”代表成功，“0”代表失败
		String money = request.getParameter("money");// 支付金额，单位：元。
		String order = request.getParameter("order");// 本次支付的订单号。
		String mid = request.getParameter("mid");// 游戏编号--同步游戏联运平台为游戏分配的唯一编号本次支付用户的乐号，既登录后返回的mid参数
		String time = request.getParameter("time");// 时间戳，格式：yyyymmddHH24mmss月日小时分秒小于10前面补充0
		String signature = request.getParameter("signature");// MD5验证串，用于与接口生成的验证串做比较，保证计费通知的合法性。
		// 具体步骤见下节：如何验证通知合法性
		String ext = request.getParameter("ext");// 发起支付请求时传递的eif参数，此处原样返回(为游戏订单号)

		String msg = "order=" + order + "&money=" + money + "&mid=" + mid
				+ "&time=" + time + "&result=" + result + "&ext=" + ext
				+ "&key=" + CommParams.getInstance().getPay_key_dl();
		memlogger.info("本次消费信息(当乐):" + msg);
		String sign2 = TestMd5.md5_32(msg).toLowerCase();
		if (signature.equals(sign2))
		{
			if ("1".equals(result))
			{
				// 更新订单信息
				PayOrder po = null;
				try
				{
					po = commDao.getPayOrder(StringUtil.getInt(ext));
					if (po == null)
					{
						errorlogger.error("没有这个订单:" + StringUtil.getInt(ext));
					} else
					{
						po.setStatus(1);
						commDao.saveOrUpdate(po);
					}
				} catch (Exception e)
				{
					errorlogger.error("更新订单信息出错", e);
				}
				// 保存支付信息
				String serverId = "";
				String extraData = null;
				PayInfo pi = null;
				try
				{
					if (po != null)
					{
						extraData = po.getExtra();
						serverId = po.getServerId();
					}
					// 保存支付记录
					pi = PayInfo.createPayInfo(mid, StringUtil
							.getDateTime(System.currentTimeMillis()), "1",
							money, extraData, serverId, order, ext);
					commDao.save(pi);
				} catch (Exception e)
				{
					errorlogger.error("保存支付信息出错", e);
				}
				// 通知游戏服务器
				try
				{
					if (extraData != null)
					{
						PayExtraJson pej = JSON.toJavaObject(JSON
								.parseObject(extraData), PayExtraJson.class);
						RechargeData rData =RechargeData.getRechargeData(pej.rechargeId);
						if(rData.cost ==(int)StringUtil.getDouble(money))
						{
							notifyGameServer(serverId, pej.playerId + "",
									pej.rechargeId + "", money);
						}
						else
						{
							memlogger.info("玩家非法充值：支付"+money+"应该"+rData.cost);
						}
						
					}
				} catch (Exception e)
				{
					errorlogger.error("通知游戏服务器出错", e);
				}
				// 通知talkingdata
				notifyTalkingData(pi);
			}
		} else
		{
			memlogger.info("当乐sign:" + signature);
			memlogger.info("本地sign:" + sign2);
		}
		// 返回response
		PrintWriter out = null;
		try
		{
			response.setContentType("text/html;charset=UTF-8");
			out = response.getWriter();
			out.println("success");
			out.flush();
		} catch (Exception e)
		{
			errorlogger.error("返回信息出错", e);
		} finally
		{
			out.close();
		}
		return null;
	}

	// ==itools==//
	public ModelAndView pay_it(HttpServletRequest request,
			HttpServletResponse response)
	{
		// 获得通知参数
		String notifyData = request.getParameter("notify_data");
		String sign = request.getParameter("sign");
		boolean verified = false;
		String notifyJson = "";
		try
		{
			// 公钥RSA解密后的json字符串
			// 解密后的json格式:
			// {"order_id_com":"2013050900000712","user_id":"10010","amount":"0.10","account":"test001","order_id":"2013050900000713","result":"success"}
			notifyJson = RSASignature.decrypt(notifyData);
			// 公钥对数据进行RSA签名校验
			verified = RSASignature.verify(notifyJson, sign);
		} catch (Exception e)
		{
			errorlogger.error("解密签名出错", e);
			verified = false;
		}
		memlogger.info("本次消费信息(itools):" + notifyJson);
		if (verified)
		{
			// 签名校验成功, 可以解析notifyJson, 做逻辑处理, 比如给相应用户增加宝石
			ItoolsPayJson pj = JSON.toJavaObject(JSON.parseObject(notifyJson),
					ItoolsPayJson.class);
			if ("success".equals(pj.result))
			{
				// 更新订单信息
				PayOrder po = null;
				try
				{
					po = commDao
							.getPayOrder(StringUtil.getInt(pj.order_id_com));
					if (po == null)
					{
						errorlogger.error("没有这个订单:"
								+ StringUtil.getInt(pj.order_id_com));
					} else
					{
						po.setStatus(1);
						commDao.saveOrUpdate(po);
					}
				} catch (Exception e)
				{
					errorlogger.error("更新订单信息出错", e);
				}
				// 保存支付信息
				String serverId = "";
				String extraData = null;
				PayInfo pi = null;
				try
				{
					if (po != null)
					{
						extraData = po.getExtra();
						serverId = po.getServerId();
					}
					// 保存支付记录
					pi = PayInfo.createPayInfo(pj.user_id, StringUtil
							.getDateTime(System.currentTimeMillis()), "1",
							pj.amount, extraData, serverId, pj.order_id,
							pj.order_id_com);
					commDao.save(pi);
				} catch (Exception e)
				{
					errorlogger.error("保存支付信息出错", e);
				}
				// 通知游戏服务器
				try
				{
					if (extraData != null)
					{
						PayExtraJson pej = JSON.toJavaObject(JSON
								.parseObject(extraData), PayExtraJson.class);
						RechargeData rData =RechargeData.getRechargeData(pej.rechargeId);
						if(rData.cost ==(int)StringUtil.getDouble(pj.amount))
						{
							notifyGameServer(serverId, pej.playerId + "",
									pej.rechargeId + "", pj.amount);
						}
						else
						{
							memlogger.info("玩家非法充值：支付"+pj.amount+"应该"+rData.cost);
						}
						
					}
				} catch (Exception e)
				{
					errorlogger.error("通知游戏服务器出错", e);
				}
				// 通知talkingdata
				notifyTalkingData(pi);
			}
		} else
		{
			memlogger.info("签名校验失败(itools)");
		}
		// 返回response
		String result = "failed";
		if (verified)
		{
			result = "success";
		}
		PrintWriter out = null;
		try
		{
			response.setContentType("text/html;charset=UTF-8");
			out = response.getWriter();
			out.println(result);
			out.flush();
		} catch (Exception e)
		{
			errorlogger.error("返回信息出错", e);
		} finally
		{
			out.close();
		}
		return null;
	}

	// ==i4==//
	// http://114.215.183.102:8080/card_server_pay/pay.htm?action=pay_i4
	@SuppressWarnings("unchecked")
	public ModelAndView pay_i4(HttpServletRequest request,
			HttpServletResponse response)
	{
		String result = "fail";
		try
		{
			request.setCharacterEncoding(Constant.CHARSET);
		} catch (Exception e)
		{
			errorlogger.error("本次消费信息(i4):设置字符集出错");
		}
		// 获取爱思POST过来异步通知信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParamsTemp = request.getParameterMap();

		Map requestParams = new HashMap();
		requestParams.put("sign", requestParamsTemp.get("sign"));
		requestParams.put("status", requestParamsTemp.get("status"));
		requestParams.put("account", requestParamsTemp.get("account"));
		requestParams.put("role", requestParamsTemp.get("role"));
		requestParams.put("app_id", requestParamsTemp.get("app_id"));
		requestParams.put("billno", requestParamsTemp.get("billno"));
		requestParams.put("order_id", requestParamsTemp.get("order_id"));
		requestParams.put("zone", requestParamsTemp.get("zone"));

		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();)
		{
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++)
			{
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		// 服务器签名验证成功
		if (verifySignature(params))
		{
			memlogger.info("本次消费信息(i4):签名验证成功");
			// 请在这里加上游戏的业务逻辑程序代码
			// 获取通知返回参数，可参考接口文档中通知参数列表(以下仅供参考)
			String status = request.getParameter("status");// 交易状态
			// 交易处理成功
			if (null != status && status.equals("0"))
			{
				String order_id = request.getParameter("order_id");// 兑换订单号
				String billno = request.getParameter("billno");// 厂商订单号
				// String account=request.getParameter("account");//通行证账号
				String amount = request.getParameter("amount");// 兑换爱思币数量
				// String app_id=request.getParameter("app_id");//厂商应用id
				// String role=request.getParameter("role");//厂商应用角色id
				// String zone=request.getParameter("zone");//厂商应用分区

				// 更新订单信息
				PayOrder po = null;
				try
				{
					po = commDao.getPayOrder(StringUtil.getInt(billno));
					if (po == null)
					{
						errorlogger
								.error("没有这个订单:" + StringUtil.getInt(billno));
					} else
					{
						po.setStatus(1);
						commDao.saveOrUpdate(po);
					}
				} catch (Exception e)
				{
					errorlogger.error("更新订单信息出错", e);
				}
				// 保存支付信息
				String serverId = "";
				String extraData = null;
				PayInfo pi = null;
				// 元
				int value = (int) StringUtil.getDouble(amount);
				memlogger.info("value:" + value);
				try
				{
					if (po != null)
					{
						extraData = po.getExtra();
						serverId = po.getServerId();
					}
					// 保存支付记录
					pi = PayInfo.createPayInfo(null, StringUtil
							.getDateTime(System.currentTimeMillis()), "1",
							value + "", extraData, serverId, order_id, billno);
					commDao.save(pi);
				} catch (Exception e)
				{
					errorlogger.error("保存支付信息出错", e);
				}
				// 通知游戏服务器
				try
				{
					if (extraData != null)
					{
						PayExtraJson pej = JSON.toJavaObject(JSON
								.parseObject(extraData), PayExtraJson.class);
						RechargeData rData =RechargeData.getRechargeData(pej.rechargeId);
						if(rData.cost==value)
						{
							notifyGameServer(serverId, pej.playerId + "",
									pej.rechargeId + "", value + "");
						}
						else
						{
							memlogger.info("玩家非法充值：支付"+value+"应该"+rData.cost);
						}
						
					}
				} catch (Exception e)
				{
					errorlogger.error("通知游戏服务器出错", e);
				}
				// 通知talkingdata
				notifyTalkingData(pi);

				result = "success";
			}
		} else
		{
			memlogger.info("本次消费信息(i4):签名验证失败");
		}
		PrintWriter out = null;
		try
		{
			response.setContentType("text/html;charset=UTF-8");
			out = response.getWriter();
			out.println(result);
			out.flush();
		} catch (Exception e)
		{
			errorlogger.error("返回信息出错", e);
		} finally
		{
			out.close();
		}
		return null;
	}

	/**
	 * 异步通知消息验证
	 * 
	 * @param para
	 *            异步通知消息
	 * @return 验证结果
	 */
	private static boolean verifySignature(Map<String, String> para)
	{
		try
		{
			String respSignature = para.get(Constant.SIGNATURE);
			// 除去数组中的空值和签名参数
			Map<String, String> filteredReq = PayCore.paraFilter(para);
			Map<String, String> signature = PayCore
					.parseSignature(respSignature);
			for (String key : filteredReq.keySet())
			{
				String value = filteredReq.get(key);
				String signValue = signature.get(key);
				if (!value.equals(signValue))
				{
					return false;
				}
			}
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}

	// ==pp==//
	// http://114.215.183.102:8080/card_server_pay/pay.htm?action=pay_pp
	public ModelAndView pay_pp(HttpServletRequest request,
			HttpServletResponse response)
	{
		String order_id = request.getParameter("order_id");// 兑换订单号
		String billno = request.getParameter("billno");// 厂商订单号（原样返回给游戏服）
		String account = request.getParameter("account");// 通行证账号
		String amount = request.getParameter("amount");// 兑换PP币数数量
		String status = request.getParameter("status");// 状态:0 正常状态1,已兑换过并成功返回
		String app_id = request.getParameter("app_id");// 厂商应用ID（原样返回给游戏服）
		String uuid = request.getParameter("uuid");// 设备号（返回的uuid 为空）
		String roleid = request.getParameter("roleid");// 厂商应用角色id（原样返回给游戏服）
		String zone = request.getParameter("zone");// 厂商应用分区id（原样返回给游戏服）
		String sign = request.getParameter("sign");// 签名(RSA 私钥加密)

		memlogger.info("本次消费信息(pp):" + order_id);
		memlogger.info("本次消费信息(pp):" + billno);
		memlogger.info("本次消费信息(pp):" + account);
		memlogger.info("本次消费信息(pp):" + amount);
		memlogger.info("本次消费信息(pp):" + status);
		memlogger.info("本次消费信息(pp):" + app_id);
		memlogger.info("本次消费信息(pp):" + uuid);
		memlogger.info("本次消费信息(pp):" + roleid);
		memlogger.info("本次消费信息(pp):" + zone);
		memlogger.info("本次消费信息(pp):" + sign);

		// try
		// {
		// order_id=URLDecoder.decode(order_id, "UTF-8");
		// billno=URLDecoder.decode(billno, "UTF-8");
		// account=URLDecoder.decode(account, "UTF-8");
		// amount=URLDecoder.decode(amount, "UTF-8");
		// status=URLDecoder.decode(status, "UTF-8");
		// app_id=URLDecoder.decode(app_id, "UTF-8");
		// uuid=URLDecoder.decode(uuid, "UTF-8");
		// roleid=URLDecoder.decode(roleid, "UTF-8");
		// zone=URLDecoder.decode(zone, "UTF-8");
		// sign=URLDecoder.decode(sign, "UTF-8");
		// }
		// catch (Exception e)
		// {
		// errorlogger.error("urldecode出错", e);
		// }
		// memlogger.info("urldecode本次消费信息(pp):"+order_id);
		// memlogger.info("urldecode本次消费信息(pp):"+billno);
		// memlogger.info("urldecode本次消费信息(pp):"+account);
		// memlogger.info("urldecode本次消费信息(pp):"+amount);
		// memlogger.info("urldecode本次消费信息(pp):"+status);
		// memlogger.info("urldecode本次消费信息(pp):"+app_id);
		// memlogger.info("urldecode本次消费信息(pp):"+uuid);
		// memlogger.info("urldecode本次消费信息(pp):"+roleid);
		// memlogger.info("urldecode本次消费信息(pp):"+zone);
		// memlogger.info("urldecode本次消费信息(pp):"+sign);

		String result = "fail";
		try
		{
			RSAEncrypt rsaEncrypt = new RSAEncrypt();
			// 加载公钥
			rsaEncrypt.loadPublicKey(RSAEncrypt.DEFAULT_PUBLIC_KEY);
			BASE64Decoder base64Decoder = new BASE64Decoder();
			byte[] dcDataStr = base64Decoder.decodeBuffer(sign);
			byte[] plainData = rsaEncrypt.decrypt(rsaEncrypt.getPublicKey(),
					dcDataStr);
			sign = new String(plainData, Charset.forName("UTF-8"));

			memlogger.info("sign解密后(pp):" + sign);
			PPPayJson pj = JSON.toJavaObject(JSON.parseObject(sign),
					PPPayJson.class);
			if (pj.getOrder_id().equals(order_id)
					&& pj.getBillno().equals(billno)
					&& pj.getAccount().equals(account)
					&& pj.getAmount().equals(amount)
					&& (pj.getStatus() + "").equals(status)
					&& pj.getApp_id().equals(app_id))
			{
				if (Integer.valueOf(status) == 0)
				{
					// 更新订单信息
					PayOrder po = null;
					try
					{
						po = commDao.getPayOrder(StringUtil.getInt(billno));
						if (po == null)
						{
							errorlogger.error("没有这个订单:"
									+ StringUtil.getInt(billno));
						} else
						{
							po.setStatus(1);
							commDao.saveOrUpdate(po);
						}
					} catch (Exception e)
					{
						errorlogger.error("更新订单信息出错", e);
					}
					// 保存支付信息
					String serverId = "";
					String extraData = null;
					PayInfo pi = null;
					try
					{
						if (po != null)
						{
							extraData = po.getExtra();
							serverId = po.getServerId();
						}
						// 保存支付记录
						pi = PayInfo.createPayInfo(account, StringUtil
								.getDateTime(System.currentTimeMillis()), "1",
								amount, extraData, serverId, order_id, billno);
						commDao.save(pi);
					} catch (Exception e)
					{
						errorlogger.error("保存支付信息出错", e);
					}
					// 通知游戏服务器
					try
					{
						if (extraData != null)
						{
							PayExtraJson pej = JSON
									.toJavaObject(JSON.parseObject(extraData),
											PayExtraJson.class);
							RechargeData rData =RechargeData.getRechargeData(pej.rechargeId);
							if(rData.cost==(int)StringUtil.getDouble(amount))
							{
								notifyGameServer(serverId, pej.playerId + "",
										pej.rechargeId + "", amount);
							}
							else
							{
								memlogger.info("玩家非法充值：支付"+amount+"应该"+rData.cost);
							}
							
						}
					} catch (Exception e)
					{
						errorlogger.error("通知游戏服务器出错", e);
					}
					// 通知talkingdata
					notifyTalkingData(pi);

					result = "success";
				}
			} else
			{
				memlogger.info("验证出错(pp)");
			}
		} catch (Exception e)
		{
			errorlogger.error("解密sign出错", e);
		}
		// 返回response
		PrintWriter out = null;
		try
		{
			response.setContentType("text/html;charset=UTF-8");
			out = response.getWriter();
			out.println(result);
			out.flush();
		} catch (Exception e)
		{
			errorlogger.error("返回信息出错", e);
		} finally
		{
			out.close();
		}
		return null;
	}

	// ==快用==//
	// http://114.215.183.102:8080/card_server_pay/pay.htm?action=pay_pp
	public ModelAndView pay_ky(HttpServletRequest request,
			HttpServletResponse response)
	{
		memlogger.info("支付信息(ky)");
		try
		{
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e)
		{
			errorlogger.error("设置字符集出错(ky)", e);
		}
		// 获取快用POST过来异步通知信息
		Map<String, String> transformedMap = new HashMap<String, String>();
		String notify_data = request.getParameter("notify_data");// RSA
		// 加密的关键数据，解密后格式为：dealseq=20130219160809567&fee=0.01&payresult=0
		transformedMap.put("notify_data", notify_data);
		String orderid = request.getParameter("orderid");// 快用平台订单号
		transformedMap.put("orderid", orderid);
		String sign = request.getParameter("sign");// RSA签名
		transformedMap.put("sign", sign);
		String dealseq = request.getParameter("dealseq");// 游戏订单号
		transformedMap.put("dealseq", dealseq);
		String uid = request.getParameter("uid");// 游戏帐号
		transformedMap.put("uid", uid);
		String subject = request.getParameter("subject");// 购买物品名
		transformedMap.put("subject", subject);
		String v = request.getParameter("v");// 版本号
		transformedMap.put("v", v);
		// 将sign除外的参数按自然升序排序后组装成验签数据
		String signData = Util.getSignData(transformedMap);
		// RSA验证签名
		// 分配给开发商公钥
		String rsaPublicKey = CommParams.getInstance().getPay_key_ky();

		String result = "failed";
		// "RSA验签成功，数据可信
		if (RSASignature2.doCheck(signData, sign, rsaPublicKey, "UTF-8"))
		{
			RSAEncrypt2 rsaEncrypt = new RSAEncrypt2();
			// 加载公钥
			try
			{
				rsaEncrypt.loadPublicKey(rsaPublicKey);
				// 加载公钥成功
				// 公钥解密通告加密数据
				byte[] dcDataStr = Base64_2.decode(notify_data);
				byte[] plainData = rsaEncrypt.decrypt(
						rsaEncrypt.getPublicKey(), dcDataStr);
				// 获取到加密通告信息
				String notifyData = new String(plainData, "UTF-8");
				memlogger.info("notifyData:" + notifyData);
				// 开发商业务逻辑处理
				// dealseq=20130219160809567&fee=0.01&payresult=0
				String[] ss = notifyData.split("&");
				String[] ss0 = ss[0].split("=");
				String[] ss1 = ss[1].split("=");
				String[] ss2 = ss[2].split("=");

				String dealseq2 = ss0[1];
				String amount = ss1[1];
				String payresult = ss2[1];
				// 比较订单信息和本地信息的一致性
				if (dealseq2.equals(dealseq))
				{
					// 响应给快用
					result = "success";
					// 支付结果：payresult=0 （0：成功，其它失败）
					if ("0".equals(payresult.trim()))
					{
						// 更新订单信息
						PayOrder po = null;
						try
						{
							po = commDao
									.getPayOrder(StringUtil.getInt(dealseq));
							if (po == null)
							{
								errorlogger.error("没有这个订单:"
										+ StringUtil.getInt(dealseq));
							} else
							{
								po.setStatus(1);
								commDao.saveOrUpdate(po);
							}
						} catch (Exception e)
						{
							errorlogger.error("更新订单信息出错", e);
						}
						// 保存支付信息
						String serverId = "";
						String extraData = null;
						PayInfo pi = null;
						try
						{
							if (po != null)
							{
								extraData = po.getExtra();
								serverId = po.getServerId();
							}
							// 保存支付记录
							pi = PayInfo.createPayInfo(uid, StringUtil
									.getDateTime(System.currentTimeMillis()),
									"1", amount, extraData, serverId, orderid,
									dealseq);
							commDao.save(pi);
						} catch (Exception e)
						{
							errorlogger.error("保存支付信息出错", e);
						}
						// 通知游戏服务器
						try
						{
							if (extraData != null)
							{
								PayExtraJson pej = JSON.toJavaObject(JSON
										.parseObject(extraData),
										PayExtraJson.class);
								RechargeData rData =RechargeData.getRechargeData(pej.rechargeId);
								if(rData.cost==(int)StringUtil.getDouble(amount))
								{
									notifyGameServer(serverId, pej.playerId + "",
											pej.rechargeId + "", amount);
								}
								else
								{
									memlogger.info("玩家非法充值：支付"+amount+"应该"+rData.cost);
								}
								
							}
						} catch (Exception e)
						{
							errorlogger.error("通知游戏服务器出错", e);
						}
						// 通知talkingdata
						notifyTalkingData(pi);
					}
				}
			} catch (Exception e)
			{
				// 加载公钥失败
				errorlogger.error("加载公钥失败", e);
			}
		}
		// RSA验签失败，数据不可信
		else
		{
			memlogger.info("签名校验失败(ky)");
		}
		// 返回response
		PrintWriter out = null;
		try
		{
			response.setContentType("text/html;charset=UTF-8");
			out = response.getWriter();
			out.println(result);
			out.flush();
			memlogger.info("result(ky):" + result);
		} catch (Exception e)
		{
			errorlogger.error("返回信息出错", e);
		} finally
		{
			out.close();
		}
		return null;
	}

	// ==91==//
	// http://114.215.183.102:8080/card_server_pay/pay.htm?action=pay_pp
	public ModelAndView pay_91(HttpServletRequest request,
			HttpServletResponse response)
	{
		String AppId = request.getParameter("AppId");// 应用ID，对应游戏客户端中使用的APPID
		String Act = request.getParameter("Act");// 1
		String ProductName = request.getParameter("ProductName");// 应用名称
		if (ProductName != null && ProductName.length() > 0)
		{
			try
			{
				ProductName = new String(ProductName.getBytes("ISO8859_1"),
						"UTF-8");
			} catch (UnsupportedEncodingException e)
			{
				errorlogger.error("转码出错ProductName", e);
			}
		}
		String ConsumeStreamId = request.getParameter("ConsumeStreamId");// 消费流水号
		String CooOrderSerial = request.getParameter("CooOrderSerial");// 商户订单号
		String Uin = request.getParameter("Uin");// 91 账号ID
		String GoodsId = request.getParameter("GoodsId");// 商品ID
		String GoodsInfo = request.getParameter("GoodsInfo");// 商品名称
		if (GoodsInfo != null && GoodsInfo.length() > 0)
		{
			try
			{
				GoodsInfo = new String(GoodsInfo.getBytes("ISO8859_1"), "UTF-8");
			} catch (UnsupportedEncodingException e)
			{
				errorlogger.error("转码出错GoodsInfo", e);
			}
		}
		String GoodsCount = request.getParameter("GoodsCount");// 商品数量
		String OriginalMoney = request.getParameter("OriginalMoney");// 原始总价(格式：0.00)
		String OrderMoney = request.getParameter("OrderMoney");// 实际总价(格式：0.00)
		String Note = request.getParameter("Note");// 即支付描述（客户端API
		// 参数中的payDescription
		// 字段）购买时客户端应用通过API
		// 传入，原样返回给应用服务器开发者可以利用该字段，定义自己的扩展数据。例如区分游戏服务器
		if (Note != null && Note.length() > 0)
		{
			try
			{
				Note = new String(Note.getBytes("ISO8859_1"), "UTF-8");
			} catch (UnsupportedEncodingException e)
			{
				errorlogger.error("转码出错Note", e);
			}
		}
		String PayStatus = request.getParameter("PayStatus");// 支付状态：0=失败，1=成功
		String CreateTime = request.getParameter("CreateTime");// 创建时间(yyyy-MM-dd
		// HH:mm:ss)
		String Sign = request.getParameter("Sign");// 以上参数的MD5 值

		StringBuilder strSign = new StringBuilder();
		strSign.append(AppId);
		strSign.append(Act);
		strSign.append(ProductName);
		strSign.append(ConsumeStreamId);
		strSign.append(CooOrderSerial);
		strSign.append(Uin);
		strSign.append(GoodsId);
		strSign.append(GoodsInfo);
		strSign.append(GoodsCount);
		strSign.append(OriginalMoney);
		strSign.append(OrderMoney);
		strSign.append(Note);
		strSign.append(PayStatus);
		strSign.append(CreateTime);
		strSign.append(CommParams.getInstance().getPay_key_91());
		String str = strSign.toString();

		memlogger.info("本次消费信息(91)Sign:" + Sign);
		memlogger.info("本次消费信息(91)str:" + str);
		String sign = MD5.md5(str);

		ErrorJson ej = new ErrorJson();
		ej.ErrorCode = "1";// 接收成功
		if (!CommParams.getInstance().getAppId_91().equals(AppId))
		{
			ej.ErrorCode = "2";// appid无效
			ej.ErrorDesc = "appid无效";
		}
		if (!"1".equals(Act))
		{
			ej.ErrorCode = "3";// Act无效
			ej.ErrorDesc = "Act无效";
		}
		if (!sign.toLowerCase().equals(Sign.toLowerCase()))
		{
			ej.ErrorCode = "5";// sign无效
			ej.ErrorDesc = "sign无效";
		}
		if ("1".equals(ej.ErrorCode))
		{
			ej.ErrorDesc = "接收成功";
			if ("1".equals(PayStatus))
			{
				// 更新订单信息
				PayOrder po = null;
				try
				{
					po = commDao.getPayOrder(StringUtil.getInt(CooOrderSerial));
					if (po == null)
					{
						errorlogger.error("没有这个订单:"
								+ StringUtil.getInt(CooOrderSerial));
					} else
					{
						po.setStatus(1);
						commDao.saveOrUpdate(po);
					}
				} catch (Exception e)
				{
					errorlogger.error("更新订单信息出错", e);
				}
				// 保存支付信息
				String serverId = "";
				String extraData = null;
				PayInfo pi = null;
				try
				{
					if (po != null)
					{
						extraData = po.getExtra();
						serverId = po.getServerId();
					}
					// 保存支付记录
					pi = PayInfo.createPayInfo(Uin, StringUtil
							.getDateTime(System.currentTimeMillis()), "1",
							OrderMoney, extraData, serverId, ConsumeStreamId,
							CooOrderSerial);
					commDao.save(pi);
				} catch (Exception e)
				{
					errorlogger.error("保存支付信息出错", e);
				}
				// 通知游戏服务器
				try
				{
					if (extraData != null)
					{
						PayExtraJson pej = JSON.toJavaObject(JSON
								.parseObject(extraData), PayExtraJson.class);
						RechargeData rData =RechargeData.getRechargeData(pej.rechargeId);
						if(rData.cost ==(int)StringUtil.getDouble(OrderMoney))
						{
							notifyGameServer(serverId, pej.playerId + "",
									pej.rechargeId + "", OrderMoney);
						}
						else
						{
							memlogger.info("玩家非法充值：支付"+OrderMoney+"应该"+rData.cost);
						}
						
					}
				} catch (Exception e)
				{
					errorlogger.error("通知游戏服务器出错", e);
				}
				// 通知talkingdata
				notifyTalkingData(pi);
			}
		} else
		{
			memlogger.info("签名校验失败(91)");
		}
		// 返回response
		PrintWriter out = null;
		try
		{
			String result = JSON.toJSONString(ej);
			response.setContentType("text/html;charset=UTF-8");
			out = response.getWriter();
			out.println(result);
			out.flush();
			memlogger.info("result(91):" + result);
		} catch (Exception e)
		{
			errorlogger.error("返回信息出错", e);
		} finally
		{
			out.close();
		}
		return null;
	}

	// ==XY苹果助手==//
	// http://114.215.183.102:8080/card_server_pay/pay.htm?action=pay_pp
	// public ModelAndView pay_xy(HttpServletRequest request,HttpServletResponse
	// response)
	// {
	//		
	// return null;
	// }

	// ==蜂巢越狱官方包==//
	// http://114.215.183.102:8080/card_server_pay/pay.htm?action=pay_pp
	public ModelAndView pay_gc_ios(HttpServletRequest request,
			HttpServletResponse response)
	{

		return null;
	}

	// ==coolpad==//
	// http://114.215.183.102:8080/card_server_pay/pay.htm?action=pay_coolpad
	public ModelAndView pay_coolpad(HttpServletRequest request,
			HttpServletResponse response)
	{
		String transdata = request.getParameter("transdata");
		String sign = request.getParameter("sign");
		memlogger.info("本次消费信息(coolpad):" + transdata);
		memlogger.info("本次消费信息(coolpad)sign:" + sign);
		String result = "FAILURE";
		if (CpTransSyncSignValid.validSign(transdata, sign.trim(), CommParams
				.getInstance().getPay_key_coolpad()))
		{
			// cpprivate字段引起json解析错误,这里把cpprivate字段值替换掉,此字段没用
			int i = transdata.indexOf("cpprivate");
			int begin = transdata.indexOf("{", i);
			int end = transdata.indexOf("}", i);
			String temp = transdata.substring(begin, end + 1);
			transdata = transdata.replace(temp, "");

			CoolpadPayJson pj = JSON.toJavaObject(JSON.parseObject(transdata),
					CoolpadPayJson.class);
			// 更新订单信息
			PayOrder po = null;
			try
			{
				po = commDao.getPayOrder(StringUtil.getInt(pj.getExorderno()));
				if (po == null)
				{
					errorlogger.error("没有这个订单:"
							+ StringUtil.getInt(pj.getExorderno()));
				} else
				{
					po.setStatus(1);
					commDao.saveOrUpdate(po);
				}
			} catch (Exception e)
			{
				errorlogger.error("更新订单信息出错", e);
			}
			int price = pj.getMoney() / 100;
			// 保存支付信息
			String serverId = "";
			String extraData = null;
			PayInfo pi = null;
			try
			{
				if (po != null)
				{
					extraData = po.getExtra();
					serverId = po.getServerId();
				}
				// 保存支付记录
				pi = PayInfo.createPayInfo(null, StringUtil.getDateTime(System
						.currentTimeMillis()), "1", price + "", extraData,
						serverId, pj.getTransid(), pj.getExorderno());
				commDao.save(pi);
			} catch (Exception e)
			{
				errorlogger.error("保存支付信息出错", e);
			}
			// 通知游戏服务器
			try
			{
				if (extraData != null)
				{
					PayExtraJson pej = JSON.toJavaObject(JSON
							.parseObject(extraData), PayExtraJson.class);
					RechargeData rData =RechargeData.getRechargeData(pej.rechargeId);
					if(rData.cost==price)
					{
						notifyGameServer(serverId, pej.playerId + "",
								pej.rechargeId + "", price + "");
					}
					else
					{
						memlogger.info("玩家非法充值：支付"+price+"应该"+rData.cost);
					}
					
				}
			} catch (Exception e)
			{
				errorlogger.error("通知游戏服务器出错", e);
			}
			// 通知talkingdata
			notifyTalkingData(pi);
			result = "SUCCESS";
		} else
		{
			memlogger.info("coolpad验证失败");
			result = "FAILURE";
		}
		// 返回response
		PrintWriter out = null;
		try
		{
			response.setContentType("text/html;charset=UTF-8");
			out = response.getWriter();
			out.println(result);
			out.flush();
		} catch (Exception e)
		{
			errorlogger.error("返回信息出错", e);
		} finally
		{
			out.close();
		}
		return null;
	}

	/***
	 * 海马渠道
	 * @return
	 */
	public ModelAndView pay_hm(HttpServletRequest request ,HttpServletResponse response)
	{
		
		//获取海马post过来的异步通知消息
		String transdata =request.getParameter("transdata");
		String sign =request.getParameter("sign");
		memlogger.info("本次消费信息(haima):" + transdata);
		memlogger.info("本次消费信息(haima)sign:" + sign);
		boolean verified =false;
		verified =validSign(transdata, sign);
		if(verified)
		{
			//签名校验成功,解析transdata
			HaimaPayJson hj =JSON.toJavaObject(JSON.parseObject(transdata),HaimaPayJson.class);
			if(hj.result==0)
			{
				//更新订单信息
				PayOrder po =null;
				try
				{
					po =commDao.getPayOrder(StringUtil.getInt(hj.exorderno));
					if(po ==null)
					{
						errorlogger.error("没有这个订单："+StringUtil.getInt(hj.exorderno));	
					}
					else
					{
						po.setStatus(1);
						commDao.saveOrUpdate(po);
					}
				} catch (Exception e)
				{
					errorlogger.error("更新订单出错");
				}
				//保存支付信息
				String serverId="";
				String extraData =null;
				PayInfo pi =null;
				int value = hj.money;
				value = value / 100;
				try
				{
					if(po !=null)
					{
						extraData =po.getExtra();
						serverId =po.getServerId();
					}
					//保存支付记录
					pi =PayInfo.createPayInfo(null, StringUtil.getDateTime(System.currentTimeMillis()), "1", value+"", extraData, serverId, hj.transid, hj.exorderno);
					commDao.save(pi);
				} catch (Exception e)
				{
					errorlogger.error("保存支付信息出错",e);
				}
				//通知游戏服务器
				try
				{
					if(transdata !=null)
					{
						PayExtraJson pej =JSON.toJavaObject(JSON.parseObject(extraData), PayExtraJson.class);
						RechargeData rData =RechargeData.getRechargeData(pej.rechargeId);
						if(rData.cost==value)
						{
							notifyGameServer(serverId, pej.playerId+"", pej.rechargeId+"",value+"");
						}
						else
						{
							memlogger.info("玩家非法充值：支付"+value+"应该"+rData.cost);
						}
						
					}
				}
				catch (Exception e)
				{
					errorlogger.error("通知游戏服务器出错",e);
				}
				//通知talkdata
				notifyTalkingData(pi);
			}
		}
		else
		{
			memlogger.info("签名校验失败(haima)");
		}
		// 返回response
		String result = "FAILURE";
		if (verified)
		{
			result = "SUCCESS";
		}
		PrintWriter out = null;
		try
		{
			response.setContentType("text/html;charset=UTF-8");
			out = response.getWriter();
			out.println(result);
			out.flush();
		} catch (Exception e)
		{
			errorlogger.error("返回信息出错", e);
		} finally
		{
			out.close();
		}
		return null;
	}
	
	public static boolean validSign(String transdata ,String sign)
    {
		
    	return CpTransSyncSignValid.validSign(transdata, sign, appkey);
    }
	
	public ModelAndView get_pay_order(HttpServletRequest request,
			HttpServletResponse response)
	{
		String consumValue = request.getParameter("consumValue");
		String extra = request.getParameter("extra");
		String serverId = request.getParameter("serverId");
		String playerId = request.getParameter("playerId");
		String userId = request.getParameter("userId");

		int order = 0;
		if (ServersData.getData(serverId) != null)
		{
			PayOrder po = new PayOrder();
			po.setConsumValue(consumValue);
			po.setExtra(extra);
			po.setServerId(serverId);
			po.setPlayerId(playerId);
			po.setUserId(userId);
			po.setReqTime(StringUtil.getDateTime(System.currentTimeMillis()));
			po.setStatus(0);
			commDao.saveOrUpdate(po);
			order = po.getId();
		}
		String orderStr = order + "";
		// 同步推要求至少10位订单号
		try
		{
			if (null != extra && !"".equals(extra))
			{
				PayExtraJson pe = JSON.toJavaObject(JSON.parseObject(extra),
						PayExtraJson.class);
				if (pe.username.startsWith("TB_"))
				{
					orderStr = (order + Constant.TbOrder) + "";
				}
			}
		} catch (Exception e)
		{
			errorlogger.error("解析json出错", e);
		}
		// 返回response
		PrintWriter out = null;
		try
		{
			response.setContentType("text/html;charset=UTF-8");
			out = response.getWriter();
			out.println(orderStr);
			out.flush();
		} catch (Exception e)
		{
			errorlogger.error("返回信息出处", e);
		} finally
		{
			out.close();
		}
		memlogger.info("产生订单:" + orderStr);
		return null;
	}

	/**
	 * 通知游戏服务器 lt@2014-6-27 下午05:41:06
	 * 
	 * @param gameServerId
	 * @param playerId
	 * @param rechargeId
	 * @param consumeValue
	 */
	@SuppressWarnings("deprecation")
	public static void notifyGameServer(String gameServerId, String playerId,
			String rechargeId, String consumeValue)
	{
		try
		{
			ServersData sd = ServersData.getData(gameServerId);
			if (sd == null)
			{
				memlogger.error("没有这个游戏服:" + gameServerId);
			} else
			{
				PayBackJson pb = new PayBackJson();
				pb.playerId = playerId;
				pb.rechargeId = rechargeId;
				pb.consumeValue = consumeValue;
				String json = JSON.toJSONString(pb);
				// aes加密,base64加密
				byte[] bytes = json.getBytes("utf-8");
				byte[] afterb = Base64.encodeBase64(aesEncryptWithKey(
						CommParams.getInstance().getPay_game_key(), bytes, 0));
				String cipher = new String(afterb, "utf-8");

				String serverUrl = "http://" + sd.ip + ":" + sd.port
						+ "/card_server/receive_pay.htm?action=receive_pay";
				memlogger.info("向游戏服务器请求serverUrl:" + serverUrl);
				PostMethod req = new PostMethod(serverUrl);
				RequestEntity re = new StringRequestEntity(cipher);
				req.setRequestEntity(re);
				req
						.setRequestHeader("Content-type",
								"text/json; charset=UTF-8");
				HttpClient httpclient = new HttpClient();
				int result = httpclient.executeMethod(req);
				req.releaseConnection();
				memlogger.info("向游戏服务器请求:" + result);
			}
		} catch (Exception e)
		{
			errorlogger.error("向游戏服务器请求出错", e);
		}
	}

	/**
	 * 通知talkingdata lt@2014-6-27 下午06:01:09
	 * 
	 * @param pi
	 */
	public static void notifyTalkingData(PayInfo pi)
	{
		if (pi == null)
		{
			errorlogger.error("无法通知talkingdata");
		}
		try
		{
			String url = "http://api.talkinggame.com/api/charge/"
					+ CommParams.getInstance().getTalkingDataAppId();
			PostMethod req = new PostMethod(url);
			String json = JSON.toJSONString(TDJson.createArray(pi));
			logger.info("TDjon:" + json);
			byte[] bytes = StringUtil.compress(json);// gzip压缩

			req.setRequestEntity(new ByteArrayRequestEntity(bytes));
			HttpClient httpclient = new HttpClient();
			int result = httpclient.executeMethod(req);
			if (result == 200)
			{
				InputStream inputStream = req.getResponseBodyAsStream();
				byte[] resBytes = new byte[0];
				byte[] buff = new byte[256];
				int n = 0;
				while ((n = inputStream.read(buff)) >= 0)
				{
					int length = resBytes.length;
					byte[] bs = new byte[length + n];
					System.arraycopy(resBytes, 0, bs, 0, length);
					System.arraycopy(buff, 0, bs, length, n);
					resBytes = bs;
				}
				inputStream.close();
				String resStr = StringUtil.unCompress(resBytes);
				memlogger.info("talkingdata返回:" + resStr);
			} else
			{
				memlogger.info("通知talkingdata出错:" + result);
			}
			req.releaseConnection();
		} catch (Exception e)
		{
			errorlogger.error("通知talkingdata出错", e);
		}
	}

	private static byte[] aesEncryptWithKey(String key, byte[] input, int offset)
			throws InvalidKeyException, NoSuchAlgorithmException,
			NoSuchPaddingException, IllegalBlockSizeException,
			BadPaddingException
	{
		byte[] put = new byte[input.length];
		System.arraycopy(input, offset, put, 0, input.length);
		SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
		Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
		c.init(Cipher.ENCRYPT_MODE, skeySpec);
		byte[] encrypt = c.doFinal(put);
		return encrypt;
	}

	public static void main0(String[] args)
	{
		try
		{
			PayInfo payInfo = new PayInfo();
			payInfo.setUserId("gid43014030899");// 用户通行证账号
			payInfo.setUserNumId("1379133");
			payInfo.setGameId("43");
			payInfo.setReqtime(1403089960193L);
			payInfo.setState("1");
			payInfo.setConsumeValue("30");
			payInfo.setGameServerZone("1");
			payInfo
					.setExtraData("{\"username\":\"GC_gid43014030899\",\"playerId\":187,\"rechargeId\":3,\"os\":\"android\"}");
			payInfo.setConsumeId("3435");
			System.out.println(JSON.toJSONString(payInfo));

			String path = "C:\\Users\\litao\\Desktop\\aaa.txt";
			BufferedReader br = new BufferedReader(new FileReader(
					new File(path)));
			String json = null;
			String temp = null;
			while ((temp = br.readLine()) != null)
			{
				json = temp;
			}

			System.out.println(json);
			JSONObject jo = JSON.parseObject(json);
			PayJson pi = JSON.toJavaObject(jo, PayJson.class);
			System.out.println(pi);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * @Description: for test模拟蜂巢发送消费请求
	 * @param args
	 * @author gs
	 * @date Nov 21, 2012 2:31:24 PM
	 */
	@SuppressWarnings("deprecation")
	public static void main(String[] args)
	{
		for(int n=0;n<1;n++)
		{
			try
			{
				PayInfo payInfo = new PayInfo();
				payInfo.setUserId("test_pay");// 用户通行证账号
				payInfo.setUserNumId("");
				payInfo.setGameId("43");
				payInfo.setReqtime(1346742112296L);
				payInfo.setState("1");
				payInfo.setConsumeValue("648");
	
				PayExtraJson pej = new PayExtraJson();
				pej.username = "GC_test";
				pej.playerId = 5068;
				pej.rechargeId = 7;
				pej.os = "android";
				payInfo.setExtraData(JSON.toJSONString(pej));
	
				payInfo.setGameServerZone("1");
				payInfo.setConsumeId("123");
	
				String hehe = JSON.toJSONString(payInfo);
	
				String key = "footBALL2014SerV";// 与蜂巢约定的密钥
				byte[] b = hehe.getBytes("utf-8");
				byte[] afterb = Base64.encodeBase64(aesEncryptWithKey(key, b, 0));
				System.out.println("加密后：" + new String(afterb, "utf-8"));
				// com.bw30.portal.common.util.AES main方法生成
				try
				{
					String url = "http://121.40.97.158/card_server_pay/pay.htm?action=post";
					PostMethod req = new PostMethod(url);
					req.setRequestEntity(new StringRequestEntity(new String(afterb,
							"utf-8")));
					req.setRequestHeader("Content-type", "text/xml; charset=UTF-8");
					HttpClient httpclient = new HttpClient();
					int result = httpclient.executeMethod(req);
					System.out.println("游戏服务器返回:" + result);
					req.releaseConnection();// 释放连接
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			System.out.println(n);
		}
	}

	/**
	 * 模拟cpyy发送消费请求 lt@2014-6-27 下午06:02:48
	 * 
	 * @param args
	 */
	public static void main2(String[] args)
	{
		try
		{
			String pay_key_cpyy = "b66ef3546a952fef0ad5f18382231817";
			String pay_url = "http://114.215.238.196:8080/card_server_pay/pay.htm?action=pay_cypp";

			String uid = "1479282";
			String order_sn = "123";
			String order_number = "5";
			String amount = "30";
			String time = System.currentTimeMillis() / 1000 + "";
			String status = "1";

			String msg = "amount=" + amount + "&order_number=" + order_number
					+ "&order_sn=" + order_sn + "&status=" + status + "&time="
					+ time + "&uid=" + uid + "@" + pay_key_cpyy;
			String sign = TestMd5.md5_32(msg);
			System.out.println("sign:" + sign);

			PostMethod req = new PostMethod(pay_url);
			req.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
					"utf-8");// 设置参数字符集
			req.setParameter("uid", uid);
			req.setParameter("order_sn", order_sn);
			req.setParameter("order_number", order_number);
			req.setParameter("amount", amount);
			req.setParameter("time", time);
			req.setParameter("status", status);
			req.setParameter("sign", sign);

			HttpClient httpclient = new HttpClient();
			int result = httpclient.executeMethod(req);
			if (result == 200)
			{
				String response = req.getResponseBodyAsString();
				System.out.println("response:" + response);
			}
			req.releaseConnection();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public static void main00(String[] args)
	{
		String serverid="2";
		String amount="6.00";
		String extra="{\"username\":\"XY_370664\",\"playerId\":17349,\"rechargeId\":2,\"os\":\"ios\"}";
		String ts="1408693555";
		String uid="370664";
		String orderid="100001183_370664_1408693489_6973";
		String sing="a88fb2789ea38bfaefe47ffbeabd1205";
		
		String appKey="DsqMnaDu5B2Lvfno3XCnHvdAaOvQrHv5";
		String s=appKey+"amount="+amount+"&extra="+extra+"&orderid="+orderid+"&serverid="+serverid+"&ts="+ts+"&uid="+uid;
		String s2=MD5.md5(s).toLowerCase();
		if(s2.equals(sing))
		{
			System.out.println();
		}
	}

	/**
	 * XY渠道 lt@2014-8-21 下午05:04:13
	 * http://127.0.0.1:8080/card_server_pay/pay.htm?action=pay_xy
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView pay_xy(HttpServletRequest request,HttpServletResponse response)
	{
		String orderid = request.getParameter("orderid");
		String uid = request.getParameter("uid");
		String serverid = request.getParameter("serverid");
		String amount = request.getParameter("amount");
		String extra = request.getParameter("extra");
		String ts = request.getParameter("ts");
		String sign = request.getParameter("sign");

		String appKey="DsqMnaDu5B2Lvfno3XCnHvdAaOvQrHv5";
		String s=appKey+"amount="+amount+"&extra="+extra+"&orderid="+orderid+"&serverid="+serverid+"&ts="+ts+"&uid="+uid;
		memlogger.info("本次消费信息(XY):"+s);
		memlogger.info("本次消费信息(XY)sign:"+sign);
		String s2=MD5.md5(s).toLowerCase();
		XyResultJson json = new XyResultJson();
		json.msg="";
		if(s2.equals(sign))
		{
			PayExtraJson pej = JSON.toJavaObject(JSON.parseObject(extra),PayExtraJson.class);
			// 向游戏服务器请求
			if (amount != null)
			{
				notifyGameServer(serverid, pej.getPlayerId() + "", pej.getRechargeId()+ "", amount);
				// 保存消费信息
				PayInfo pi = PayInfo.createPayInfo(new Integer(pej.getPlayerId()).toString(),StringUtil.getDateTime(System.currentTimeMillis()),"1", amount, extra, serverid, orderid, "");
				try
				{
					commDao.save(pi);
				}
				catch (Exception e)
				{
					errorlogger.error("保存消费信息出错", e);
				}
				// 通知talkingdata
				if (pi.getState().equals("1"))
				{
					notifyTalkingData(pi);
				}
				json.ret="0";
			}
			else
			{
				memlogger.info("充值回调信息有误!");
				json.ret="8";
			}
		}
		else
		{
			memlogger.info("签名校验失败(XY)");
			json.ret="6";
		}
		String result = JSON.toJSONString(json);
		request.setAttribute("result", result);
		return new ModelAndView("result.vm");
	}
}
